﻿Imports System.Globalization

Public Partial Class frm_ReleaseCNDN
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Dim MessageType As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not (IsPostBack) Then
            MessageType = ""
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "RELEASE CN/DN "
            LoadCNDNBlock()
        End If
    End Sub

    Private Sub LoadCNDNBlock()
        Dim dt As DataTable = clsGet.GetBlock_CNDNAllRecord()
        If (dt.Rows.Count > 0) Then
            lbAlert.Visible = False
            gridCNDN.DataSource = dt
            gridCNDN.DataBind()
        Else
            lbAlert.Visible = True
            ViewState("Credit_Limit") = Nothing
            gridCNDN.DataSource = Nothing
            gridCNDN.DataBind()
            lbAlert.Text = "ไม่พบรายการ CN/DN ที่ต้องทำการปลดบล็อค"
        End If
        ViewState("Credit") = dt
    End Sub

    Private Sub gridCNDN_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridCNDN.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridCNDN.PageIndex <> 0) Then
            Index = Index Mod (gridCNDN.PageIndex * 10)
        End If

        Dim txtReleaseDate As TextBox = CType(gridCNDN.Rows(Index).FindControl("txtReleaseDate"), TextBox)
        If txtReleaseDate Is Nothing Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาระบุวันที่ที่ต้องการ Release');", True)
            Exit Sub
        ElseIf txtReleaseDate.Text = "" Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาระบุวันที่ที่ต้องการ Release');", True)
            Exit Sub
        End If
        Dim ReleaseDate As Date
        If IsDate(txtReleaseDate.Text) Then
            ReleaseDate = CDate(txtReleaseDate.Text).ToString("dd/MM/yyyy HH:mm:ss", New CultureInfo("en-US"))
            ReleaseDate.AddHours(Date.Now.Hour)
            ReleaseDate.AddMinutes(Date.Now.Minute)
            ReleaseDate.AddSeconds(Date.Now.Second)
        Else
            ReleaseDate = Date.Now.ToString("dd/MM/yyyy HH:mm:ss", New CultureInfo("en-US"))
        End If

        If (e.CommandName = "cmdRelease") Then

            Dim dt As DataTable = clsGet.GetSaleOrder_ForRelease(gridCNDN.DataKeys(Index).Values("Booking_no"), gridCNDN.DataKeys(Index).Values("sold_To"))
            'ทำการ Release CN/DN
            Dim ClassSAP As New Class_SAP
            Dim str As String = "ทำการ Release สำเร็จ "
            Dim checkRelease As Boolean = True
            Dim i As Integer = 0
            For Each dr As DataRow In dt.Rows
                Try
                    Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
                    Dim iportNumber As String = dr.Item("IM_IPORTNUM")
                    Dim ZBABI_RET As New SAP_IPORT.BAPIRET1Table
                    Dim Bill_no As String = ""
                    SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Release(iportNumber, Bill_no, ZBABI_RET)
                    Dim xx As String = ""
                    For Each de As SAP_IPORT.BAPIRET1 In ZBABI_RET

                        If de.Type = "E" Then
                            xx &= de.Message & "\n"
                        Else
                            If InStr(de.Message_V1, "KOM") = 0 Then
                                xx &= de.Message & "\n"
                            End If
                        End If
                        If MessageType <> "E" Then MessageType = de.Type

                    Next

                    ClassSAP.SAP_CLOSE(SAP_Data)

                    If xx.Trim() <> "" Then ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                    If MessageType = "E" Then checkRelease = False

                    If (Bill_no <> "") Then
                        Dim clsDB As New ClassDatabase()
                        Dim clsFc As New ClassFunction()
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Application.Lock()
                        conn.Open()
                        tran = clsDB.BeginTran(conn)
                        If (clsFc.UPDATESAP_CNDN_REQUEST(gridCNDN.DataKeys(Index).Values("Booking_no"), dr.Item("IM_IPORTNUM"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), Bill_no, ReleaseDate, conn, tran) > 0) Then
                            For Each dm As SAP_IPORT.BAPIRET1 In ZBABI_RET
                                If (clsFc.InsertSAP_Table_MESSAGE(dr.Item("IM_IPORTNUM"), "Zbapi_Iport_Sd_Cn_Dn_Release", dm.Type, dm.Id, dm.Number, dm.Message, dm.Log_No, dm.Log_Msg_No, dm.Message_V1, dm.Message_V2, dm.Message_V3, dm.Message_V4, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                        Else
                            condition = False
                        End If

                        If (condition) Then
                            i += 1
                            str &= "\r\n" & i.ToString() & ".) " & dr.Item("EX_SALES_NO") & "  Billing : " & Bill_no
                            clsDB.CommitTran(tran)

                        Else
                            clsDB.RollBackTran(tran)
                            checkRelease = False

                        End If
                        Application.UnLock()
                        conn.Dispose()
                    Else
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
                        Exit Sub
                    End If
                    System.Threading.Thread.Sleep(1000)
                Catch ex As Exception
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
                    Exit Sub
                End Try
            Next
            If (checkRelease) Then
                LoadCNDNBlock()
                'Dim dtBilling As DataTable = clsGet.GetBlock_CNDNByOne(gridCNDN.DataKeys(Index).Values("Booking_no"), gridCNDN.DataKeys(Index).Values("sold_To"))
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & str & "');", True)
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการทำการ Release ');", True)
            End If
        ElseIf (e.CommandName = "cmdClear") Then
            Dim dt As DataTable = clsGet.GetSaleOrder_ForRelease(gridCNDN.DataKeys(Index).Values("Booking_no"), gridCNDN.DataKeys(Index).Values("sold_To"))
            'ทำการ Clear CN/DN
            Dim str As String = "ทำการ Clear ข้อมูลสำเร็จ "
            Dim checkRelease As Boolean = True
            Dim i As Integer = 0

            For Each dr As DataRow In dt.Rows
                Try
                    Dim iportNumber As String = dr.Item("IM_IPORTNUM")
                    If (iportNumber <> "") Then
                        Dim clsDB As New ClassDatabase()
                        Dim clsFc As New ClassFunction()
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Application.Lock()
                        conn.Open()
                        tran = clsDB.BeginTran(conn)
                        If (clsFc.UPDATESAP_CNDN_REQUEST(gridCNDN.DataKeys(Index).Values("Booking_no"), dr.Item("IM_IPORTNUM"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), "", ReleaseDate, conn, tran) > 0) Then
                            condition = True
                        Else
                            condition = False
                        End If

                        If (condition) Then
                            i += 1
                            str &= "\r\n" & i.ToString() & ".) " & dr.Item("EX_SALES_NO")
                            clsDB.CommitTran(tran)
                        Else
                            clsDB.RollBackTran(tran)
                            checkRelease = False
                        End If
                        Application.UnLock()
                        conn.Dispose()
                    Else
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล ');", True)
                        Exit Sub
                    End If
                    System.Threading.Thread.Sleep(1000)
                Catch ex As Exception
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Connection Lost ');", True)
                    Exit Sub
                End Try
            Next
            If (checkRelease) Then
                LoadCNDNBlock()
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & str & "');", True)
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการทำการ Clear ข้อมูล ');", True)
            End If
        End If
    End Sub
    Private Sub gridCNDN_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridCNDN.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim Li As Literal = CType(e.Row.FindControl("LiCredit"), Literal)
            If (gridCNDN.DataKeys(e.Row.RowIndex).Values("Booking_no") & "" <> "") Then
                Dim dt As DataTable = clsGet.GetBlock_CNDNByOne(gridCNDN.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridCNDN.DataKeys(e.Row.RowIndex).Values("sold_To"))
                Dim dtName As DataTable = clsGet.Get_Customer(gridCNDN.DataKeys(e.Row.RowIndex).Values("sold_To"))
                Dim Name As String
                If (dtName.Rows.Count > 0) Then
                    Name = dtName.Rows(0).Item("NAME1") & " " & dtName.Rows(0).Item("NAME2") & " " & dtName.Rows(0).Item("NAME3")
                Else
                    Name = dt.Rows(0).Item("MAgent_Name") & ""
                End If
                Li.Text = GenHTML_Credit_Limit(dt, gridCNDN.DataKeys(e.Row.RowIndex).Values("Booking_no"), Name)
            End If

        End If
    End Sub

    Private Function GenHTML_Credit_Limit(ByVal dt As DataTable, ByVal Booking_no As String, ByVal Name As String) As String
        Dim HTML As String = ""
        If (dt.Rows.Count > 0) Then
            HTML = "<table width='100%' border='1' cellpadding='2' cellspacing='0'>"
            HTML &= "<tr style='background-color:#bdeafa;'>"
            HTML &= "<td align='center'><font class='White-Style' style='color:#000000'>" & Name & "</font></td>"
            HTML &= "<td colspan='2' align='center'><font class='White-Style' style='color:#000000'>DN</font></td>"
            HTML &= "<td colspan='2' align='center'><font class='White-Style' style='color:#000000'>CN</font></td>"
            HTML &= "<td  style='width:150px;' align='left'>&nbsp;</td>"
            HTML &= "</tr>"
            HTML &= "<tr  style='background-color:#bdeafa;'>"
            HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>BILLING NO : " & dt.Rows(0).Item("IM_REF_DOC") & "</font></td>"
            HTML &= "<td style='width:150px;' align='center'><font class='White-Style' style='color:#000000'>ปริมาณ</font></td>"
            HTML &= "<td style='width:150px;' align='center'><font class='White-Style' style='color:#000000'>ราคา</font></td>"
            HTML &= "<td style='width:150px;' align='center'><font class='White-Style' style='color:#000000'>ปริมาณ</font></td>"
            HTML &= "<td style='width:150px;' align='center'><font class='White-Style' style='color:#000000'>ราคา</font></td>"
            HTML &= "<td style='width:150px;' align='center'><font class='White-Style' style='color:#000000'>Booking No. : " & Booking_no & "</font></td>"
            HTML &= "</tr>"

            Dim SumDN As String = "0"
            Dim SumCN As String = "0"
            For Each dr As DataRow In dt.Rows
                Dim DN_QTY As String = ""
                Dim DN_Price As String = ""
                Dim CN_QTY As String = ""
                Dim CN_Price As String = ""
                If (dr.Item("IM_REASON") & "" = "Z03") Then
                    If (dr.Item("IM_DOCTYPE") = "ZCR") Then
                        CN_QTY = dr.Item("Target_Qty")
                        CN_Price = CDbl(dr.Item("Amount")) * CDbl(CN_QTY)
                        SumCN = (CDbl(SumCN) + CDbl(CN_Price)).ToString("#####################00.00")
                    Else
                        DN_QTY = dr.Item("Target_Qty")
                        DN_Price = CDbl(dr.Item("Amount")) * CDbl(DN_QTY)
                        SumDN = (CDbl(SumDN) + CDbl(DN_Price)).ToString("#####################00.00")
                    End If
                Else
                    If (dr.Item("Target_QU") & "" = "JOB") Then
                        If (dr.Item("IM_DOCTYPE") = "ZCR") Then
                            'Z02
                            ' CN_QTY = dr.Item("Target_Qty")
                            CN_QTY = ""
                            CN_Price = dr.Item("Amount")
                            SumCN = (CDbl(SumCN) + CDbl(CN_Price)).ToString("#####################00.00")
                        Else
                            'Z01 
                            ' DN_QTY = dr.Item("Target_Qty")
                            CN_QTY = ""
                            DN_Price = dr.Item("Amount")
                            SumDN = (CDbl(SumDN) + CDbl(DN_Price)).ToString("#####################00.00")
                        End If
                    Else
                        Dim dw As DataTable = clsGet.GetBookingTariff_Actual(Booking_no, dr.Item("Material"), "")
                        If (dr.Item("IM_DOCTYPE") = "ZCR") Then
                            'Z01ใหม่น้อยกว่า
                            ' CN_QTY = dr.Item("Target_Qty")
                            CN_QTY = ""

                            If (dw.Rows.Count > 0) Then
                                CN_Price = ((CDbl(dr.Item("Amount") + CDbl(dw.Rows(0).Item("data2")))) * CDbl(dr.Item("Target_Qty"))) - (CDbl(dr.Item("Amount")) * CDbl(dr.Item("Target_Qty")))
                            Else
                                CN_Price = (CDbl(dr.Item("Amount")) * CDbl(dr.Item("Target_Qty")))
                            End If

                            SumCN = (CDbl(SumCN) + CDbl(CN_Price)).ToString("######################0.00")
                        Else
                            'Z02  
                            ' DN_QTY = dr.Item("Target_Qty")
                            CN_QTY = ""
                            If (dw.Rows.Count > 0) Then
                                DN_Price = (CDbl(dr.Item("Amount")) * CDbl(dr.Item("Target_Qty"))) - ((CDbl(dr.Item("Amount") - CDbl(dw.Rows(0).Item("data2")))) * CDbl(dr.Item("Target_Qty")))
                            Else
                                DN_Price = (CDbl(dr.Item("Amount")) * CDbl(dr.Item("Target_Qty")))
                            End If
                            SumDN = (CDbl(SumDN) + CDbl(DN_Price)).ToString("######################0.00")
                        End If
                    End If

                End If
                Try
                    DN_QTY = FormatNumber(DN_QTY)
                Catch ex As Exception

                End Try
                Try
                    DN_Price = FormatNumber(DN_Price)
                Catch ex As Exception

                End Try
                Try
                    CN_QTY = FormatNumber(CN_QTY)
                Catch ex As Exception

                End Try
                Try
                    CN_Price = FormatNumber(CN_Price)
                Catch ex As Exception

                End Try
                HTML &= "<tr>"
                HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & dr.Item("Text_Line") & "</font>&nbsp;</td>"
                HTML &= "<td style='width:150px;' align='right'>&nbsp;<font class='White-Style' style='color:#000000'>" & DN_QTY & "</font></td>"
                HTML &= "<td style='width:150px;' align='right'>&nbsp;<font class='White-Style' style='color:#000000'>" & DN_Price & "</font></td>"
                HTML &= "<td style='width:150px;' align='right'>&nbsp;<font class='White-Style' style='color:#000000'>" & CN_QTY & "</font></td>"
                HTML &= "<td style='width:150px;' align='right'>&nbsp;<font class='White-Style' style='color:#000000'>" & CN_Price & "</font></td>"
                HTML &= "<td style='width:150px;' align='right'>&nbsp;<font class='White-Style' style='color:#000000'>" & dr.Item("EX_SALES_NO") & "</font></td>"
                HTML &= "</tr>"
            Next

            Try
                SumDN = FormatNumber(SumDN)
            Catch ex As Exception

            End Try
            Try
                SumCN = FormatNumber(SumCN)
            Catch ex As Exception

            End Try

            HTML &= "<tr  style='background-color:#bdeafa;'>"
            HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>TOTAL :</font>&nbsp;</td>"
            HTML &= "<td style='width:150px;' align='center'>&nbsp;</td>"
            HTML &= "<td style='width:150px;' align='right'><font class='White-Style' style='color:#000000'>" & SumDN & "</font></td>"
            HTML &= "<td style='width:150px;' align='center'>&nbsp;</td>"
            HTML &= "<td style='width:150px;' align='right'><font class='White-Style' style='color:#000000'>" & SumCN & "</font></td>"
            HTML &= "<td style='width:150px;' align='right'><font class='White-Style' style='color:#000000'>" & CDbl(SumDN - SumCN).ToString("####################0.00") & "</font></td>"
            HTML &= "</tr>"
            HTML &= "</table>"
        End If
        Return HTML
    End Function

    Private Sub gridCNDN_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridCNDN.RowEditing

    End Sub


    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub
End Class